#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int wfd)
{
    char c = 'A';
    for (int cnt = 0; cnt < 5; ++cnt)
    {
        write(wfd, &c, 1); // 每次写一个字节
        printf("child write: %c (%d)\n", c, cnt);
        c++;
        sleep(1);
    }
    close(wfd); // 写完后关闭写端，通知父进程 EOF
    exit(0);    // 正常退出
}

void FatherRead(int rfd)
{
    char buffer[2] = {0}; // 每次读一个字节
    ssize_t n = 0;
    while ((n = read(rfd, buffer, 1)) > 0) // 每次读一个字节
    {
        buffer[n] = 0;
        std::cout << "father read: " << buffer << std::endl;
    }

    if (n == 0)
    {
        std::cout << "[father] child closed pipe (EOF)" << std::endl;
    }
    else if (n < 0)
    {
        perror("read error");
    }

    close(rfd);
}

int main()
{
    int fds[2] = {0};
    if (pipe(fds) < 0)
    {
        perror("pipe error");
        return 1;
    }

    pid_t pid = fork();
    if (pid == 0)
    {
        close(fds[0]);      // 子进程关闭读端
        ChildWrite(fds[1]); // 写数据并退出
    }

    // 父进程
    close(fds[1]);      // 父进程关闭写端
    FatherRead(fds[0]); // 读取数据

    int status = 0;
    pid_t ret = waitpid(pid, &status, 0);
    if (ret > 0)
    {
        printf("exit code: %d, exit signal: %d\n", (status >> 8) & 0xFF, status & 0x7F);
    }

    return 0;
}
